//
// Created by none98 on 2021/9/23.
//

#include <GameServer.h>
#include <Context.h>
#include <spdlog/spdlog.h>
#include "CreateRoleService.h"
#include "CreateRole.pb.h"

void CreateRoleService::Serve(TcpConnectionPtr conn, std::string message) {
    CreateRoleRequest req;
    CreateRoleResponse res;
    std::string response;

    req.ParseFromString(message);
    Context* context = static_cast<Context*>(conn->GetContext());

    if(context->GetUid()!=req.token()) {
        spdlog::info("token authority failed in CreateRoleReq");
        res.set_status(GameServer::StatusCode::authFailed);
    }else{
        //handle database;
        sql::Connection* sqlConn = context->GetDbConnection();
        try{
            std::string sql = "INSERT INTO game_user_role VALUES(?,?,?,?,?)";
            std::unique_ptr<sql::PreparedStatement> statement(sqlConn->prepareStatement(sql));
            statement->setInt64(1,req.token());
            statement->setString(2,req.rolename());
            statement->setInt(3,0);
            statement->setInt(4,0);
            statement->setInt(5,0);
            if(statement->executeUpdate()==0){
                spdlog::info("uid:{} create role fail",req.token());
            }else{
                context->SetCreated(true);
            }
            //set res
            res.set_status(GameServer::StatusCode::success);
        }catch(sql::SQLException &e){
            spdlog::error("uid:{},{}",req.token(),e.what());
        }
        context->CloseDbConnection(sqlConn);
    }

    std::string proto =std::move(res.SerializeAsString());
    int length = htonl(8+proto.size());
    int type = htonl(GameServer::ProtoType::createRoleRes);
    response.append(reinterpret_cast<char*>(&length),4);
    response.append(reinterpret_cast<char*>(&type),4);
    response.append(proto);
    conn->Send(response);
}
